<!--
 * @Description:
 * @Author: zhailei
 * @Date: 2021-07-09 09:14:57
 * @LastEditTime: 2021-07-09 13:40:27
 * 
 * @FilePath: \-cloud-vue\src\pages\system\sysAppBasics\listPage.vue
-->
<template>
  <div class="padding data-set">
    <div class="card-box">
      <div
        :class="{
          'card-item': true,
          'card-selected': cardKey == 1,
          'card-item-disable': isEdit,
        }"
        @click="cardClick(1)"
      >
        <div class="img-box">
          <img src="~@/assets/img/report02.png" />
        </div>
        <div class="text-box">
          <div class="title">
            {{ $ct("SystemCreatesTable", "系统自动创数据表") }}
          </div>
        </div>
      </div>
      <div
        :class="{
          'card-item': true,
          'card-selected': cardKey == 2,
          'card-item-disable': isEdit,
        }"
        @click="cardClick(2)"
      >
        <div class="img-box">
          <img src="~@/assets/img/report01.png" />
        </div>
        <div class="text-box">
          <div class="title">
            {{ $ct("SelectDatabaseTable", "选择本地的数据库表") }}
          </div>
        </div>
      </div>
    </div>
    <div style="text-align: center;" v-if="cardKey == 1">
      <a-input
        :addon-after="$ct('tableName', '表名')"
        v-model="randomTableName"
        :disabled="isEdit"
        style="width: 600px;"
      />
    </div>
    <template v-if="cardKey == 2">
      <a-button
        class="margin-bottom-xs"
        type="primary"
        @click="() => (tableVisible = true)"
        >{{ $ct("choice", "选择") }}</a-button
      >
      <a-table
        size="small"
        :columns="$toI18nFormat(columns)"
        :data-source="dataSource"
        :pagination="false"
        :scroll="{ y: 'calc(50vh - 100px)' }"
      >
        <template
          v-for="(item, index) in $toI18nFormat(columns)"
          :slot="item.slotName"
        >
          <span>{{ $ct(item.slotName, item.defaultTitle) }}</span>
        </template>

        <template slot="renderSort" slot-scope="text, record, index">
          <a-icon
            type="arrow-up"
            class="margin-right-xs"
            :class="[index == 0 ? 'arrowHidden' : 'arrowShow']"
            @click="arrowButton(record, index, 'up')"
          />
          <a-icon
            type="arrow-down"
            :class="[
              index == dataSource.length - 1 ? 'arrowHidden' : 'arrowShow',
            ]"
            @click="arrowButton(record, index, 'down')"
          />
        </template>
        <template
          slot="renderAssociatedFields"
          slot-scope="text, record, index"
        >
          <a-select
            style="width: 80%"
            v-model="record['associatedFields']"
            @dropdownVisibleChange="(e) => associatedFieldsDropdown(e, index)"
            @change="handleChange($event, record, 'associatedFields')"
          >
            <a-select-option
              v-for="item in columnData[index]"
              :key="item.columnName"
            >
              {{
                item.remarks
                  ? item.remarks + "(" + item.columnName + ")"
                  : item.columnName
              }}
            </a-select-option>
          </a-select>
        </template>
        <template slot="renderPrimarySubTable" slot-scope="text, record, index">
          {{ index == 0 ? $ct("mainTable", "主表") : $ct("subTable", "子表") }}
        </template>
        <template slot="renderAction" slot-scope="text, record, index">
          <a @click="handleDelete(index)" class="action-delete">{{
            $ct("delete", "删除")
          }}</a>
        </template>
      </a-table>
    </template>
    <tableModal
      ref="tableModal"
      :key="Date.now().valueOf()"
      :visible="tableVisible"
      @ok="selector"
      @cancel="() => (tableVisible = false)"
    />
  </div>
</template>

<script>
import pick from "lodash.pick";
import tableModal from "./tableModal";
export default {
  components: { tableModal },
  props: {
    isEdit: {
      type: Boolean,
      require: true,
    },
  },
  data() {
    return {
      columns: [
        {
          dataIndex: "sort",
          title: "排序",
          width: 80,
          align: "center",
          scopedSlots: {
            customRender: "renderSort",
          },
        },
        {
          title: "表名称",
          dataIndex: "tableName",
          langCode: "tableName",
        },
        {
          title: "表注释",
          dataIndex: "tableRemarks",
          langCode: "tableNotes",
        },
        {
          title: "关联字段",
          dataIndex: "associatedFields",
          width: 300,
          scopedSlots: { customRender: "renderAssociatedFields" },
        },
        {
          title: "类型",
          dataIndex: "primarySubTable",
          scopedSlots: { customRender: "renderPrimarySubTable" },
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "renderAction" },
        },
      ],
      dataSource: [],
      form: this.$form.createForm(this),
      tableVisible: false,
      cardKey: 1,
      columnData: [],
      randomTableName: "",
      databaseUuid: "",
      tableName: "",
    };
  },
  computed: {},
  watch: {},
  mounted() {},
  methods: {
    loadData(options) {
      let data = JSON.parse(options.databaseJson);
      this.cardKey = data.type;
      if (data.type == 1) {
        this.randomTableName = data.tableName;
      } else {
        this.dataSource = data.dataSource;
        this.columnData = data.columnData;
        this.databaseUuid = data.databaseUuid;
      }
      this.dataSource.forEach((item, index) => {
        this.associatedFieldsDropdown(true, index);
      });
    },
    associatedFieldsDropdown(e, index) {
      if ((e && !this.columnData[index]) || this.isEdit) {
        this.$post("/system/sysDatabaseConnection/getColumn", {
          uuid: this.databaseUuid,
          tableName: this.dataSource[index].tableName,
        }).then((res) => {
          this.$set(this.columnData, index, res);
        });
      }
    },
    handleDelete(index) {
      this.dataSource.splice(index, 1);
      this.columnData.splice(index, 1);
      this.$emit("change");
    },
    // 列表表格排序
    arrowButton(record, index, type) {
      const listData = [...this.dataSource];
      const columnData = [...this.columnData];
      let key = listData.findIndex((val) => val.tableName == record.tableName);
      if (type == "up" && index != 0) {
        // 左边是元素在数组中的原本的排列顺序 右边是自己希望的排列顺序。
        [listData[key - 1], listData[key]] = [listData[key], listData[key - 1]];
        [columnData[key - 1], columnData[key]] = [
          columnData[key],
          columnData[key - 1],
        ];
      } else if (type == "down" && index != listData.length - 1) {
        [listData[key], listData[key + 1]] = [listData[key + 1], listData[key]];
        [columnData[key], columnData[key + 1]] = [
          columnData[key + 1],
          columnData[key],
        ];
      }
      this.dataSource = listData;
      this.columnData = columnData;
    },
    cardClick(e) {
      if (this.isEdit) {
        return this.$message.warn("不可以更换数据表", 1.5);
      }
      this.cardKey = e;
      if (e == 1) {
        this.generateTableName();
      } else {
        // return this.$message.info("敬请期待！", 1.5)
        this.dataSource = [];
      }
    },
    validateData() {
      let data = {};
      this.form.validateFields((errors, values) => {
        if (!errors) {
          data = values;
        } else {
          data = null;
        }
      });
      return data;
    },
    getDataBase() {
      let obj = {};
      if (this.cardKey == 1) {
        obj = {
          type: this.cardKey,
          tableName: this.randomTableName,
        };
      } else {
        obj = {
          type: this.cardKey,
          columnData: this.columnData,
          dataSource: this.dataSource,
          databaseUuid: this.databaseUuid,
        };
      }
      return obj;
    },
    handleChange(e, record, key) {
      record[key] = e;
    },
    selector(rows, key, uuid) {
      this.dataSource = this.dataSource.concat(rows);
      if (this.dataSource.length) {
        // 数组对象去重
        var obj = {};
        this.dataSource = this.dataSource.reduce(function(item, next) {
          obj[next.tableName]
            ? ""
            : (obj[next.tableName] = true && item.push(next));
          return item;
        }, []);
      }
      this.databaseUuid = uuid;
      this.$emit("change");
    },
    /**
     * 随机生成表名接口，携带基础配置表单中的名称
     * */
    generateTableName() {
      this.$post("/form/formDatabase/generateRandomTableName", {
        name: this.tableName,
      }).then((res) => {
        this.randomTableName = res;
      });
    },
  },
  created() {},
};
</script>

<style lang="scss" scoped>
// .ant-form{
// 	border-radius: 10px;
// 	min-height: 500px;
// 	margin: 0 auto;
// 	padding: 30px 20px 50px 20px;
// 	box-shadow: 1px 2px 8px #e8e8e8;
// }

.data-set {
  height: calc(100vh - 76px);
  margin: 10px;
  background-color: #fff;
}

.col-box {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  height: calc(100vh - 116px);
}

.card-box {
  display: flex;
  justify-content: space-evenly;
  margin: 0 auto 30px;
  width: 50%;
}

.card-item {
  transition: 0.3s all;
  cursor: pointer;
  width: 181px;
  border: 1px solid #f0f2f5;
  border-radius: 10px;
  .img-box {
    padding: 40px 20px 20px;
    img {
      width: 100%;
    }
  }
}

.card-selected {
  border: 1px solid #1890ff;
  border-radius: 10px;
}

.card-item:hover {
  transform: scale(1.02);
  box-shadow: 3px 5px 15px rgba(40, 40, 40, 0.36);
}

.card-item-disable {
  box-shadow: none !important;
}

.card-item-disable:hover {
  transform: scale(1) !important;
}

.text-box {
  text-align: center;
  margin-bottom: 20px;
  .title {
    display: inline-block;
    margin-right: 10px;
    font-size: 16px;
    color: #171a1d;
    font-weight: 600;
  }
}

.arrowHidden {
  color: #e7e7e7;
}

.arrowShow {
  color: #606266;
  &:hover {
    color: #1890ff;
  }
}
</style>
